//
//  LoginViewController.m
//  LocomotiveGuards
//
//  Created by admin on 15/11/13.
//  Copyright (c) 2015年 REDOOR. All rights reserved.
//

#import "LoginViewController.h"
#import "PopMsg.h"
#import "PopLoadMsg.h"
#import "RootviewConrtoller.h"
#import "TouristViewController.h"
#import "RegisterViewController.h"
#import "ForgetpwdViewController.h"
#import "CaptchaView.h"
#import "APService.h"
#import "CheckCodeSlider.h"
#import "SaveManager.h"

#define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
#define kNumbers     @"0123456789"

@interface LoginViewController ()
{
    UIImageView *image_phone;
    UIImageView *image_phone_icon;
    UIImageView *image_code;
    UIImageView *image_pwd;
    UIImageView *image_pwd_icon;
    UIImageView *image_code_icon;
    NSInteger intforce;
    NSString *newvesionurl;
    UIAlertView *alert0;
    UIAlertView *alert1;
    BOOL start;
    BOOL end;
    CaptchaView *_captchaView;
    UIImageView *slideImgView;
    BOOL isDrop; // 判断是否出现下拉框
   // UITextField *_input;
}
@property(strong,nonatomic)UIImageView *imageview;
@property(strong,nonatomic)UIButton *btn_register;
@property(strong,nonatomic)UIButton *btn_forgetpwd;
@property(strong,nonatomic)UIButton *btn_login;
@property(strong,nonatomic)UIButton *btn_tourist_login;
@property(strong,nonatomic)UIButton *btn_pwd_security;
@property(strong,nonatomic)UITextField *filed_phone;
@property(strong,nonatomic)UITextField *field_pwd;
@property(strong,nonatomic)UITextField *input;
@property (nonatomic, strong)CheckCodeSlider *slider;
@property (nonatomic, strong)UILabel *charactersLabel;
@property (nonatomic, strong)UIScrollView *dropScrollView;
@property (nonatomic, strong)UIButton *dropButton;
@property (nonatomic, strong)NSMutableArray *btnArray; // 添加选择号码按钮数组
@property (nonatomic, strong) NSString *userOrTourist; // 判断是APP用户登录还是游客登录，0为游客登录，1问APP用户登录
@property (nonatomic) int dropValue; // 判断下拉框出现的方式，1点击按钮出现，0输入提示出现
@property (nonatomic, strong) NSMutableArray *phoneArr;
@property (nonatomic, strong) NSMutableArray *tempArr; // 暂时存储匹配的号码

@end

@implementation LoginViewController
@synthesize imageview,btn_forgetpwd,btn_login,btn_register,btn_tourist_login,btn_pwd_security,field_pwd,filed_phone;

- (NSMutableArray *)btnArray {

    if (_btnArray == nil) {
        self.btnArray = [NSMutableArray array];
    }
    return _btnArray;
}

- (NSMutableArray *)phoneArr {

    if (_phoneArr == nil) {
        self.phoneArr = [NSMutableArray array];
    }
    return _phoneArr;
}

- (NSMutableArray *)tempArr {

    if (_tempArr == nil) {
        self.tempArr = [NSMutableArray array];
    }
    return _tempArr;
}

- (instancetype)init{
    self=[super init];
    if(self){
        [self dorequestforCheckVersion];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    
    isDrop = NO;
    imageview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    imageview.image=[UIImage imageNamed:@"2pic_bg"];
    imageview.userInteractionEnabled=YES;
    [self.view addSubview:imageview];
    [self configview];
}

-(void)configview{
    //构建试图
    
    image_phone=[[UIImageView alloc]initWithFrame:CGRectMake(30*W, SCREEN_HEIGHT/2+30*H, SCREEN_WIDTH-60*W, 30*H)];
    image_phone.image=[UIImage imageNamed:@"2pic_input"];
    [imageview addSubview:image_phone];
    
    image_phone_icon=[[UIImageView alloc]initWithFrame:CGRectMake(45*W, SCREEN_HEIGHT/2+35*H, 20*H, 20*H)];
    image_phone_icon.image=[UIImage imageNamed:@"2pic_icon01"];
    [imageview addSubview:image_phone_icon];
    
    filed_phone=[[UITextField alloc]initWithFrame:CGRectMake(50*W+20*H, SCREEN_HEIGHT/2+35*H, SCREEN_WIDTH-150*W, 20*H)];
    filed_phone.placeholder=@"请输入电话号码";
    filed_phone.textColor=[UIColor whiteColor];
    filed_phone.font=[UIFont systemFontOfSize:13];
    [filed_phone addTarget:self action:@selector(keyboard_exit) forControlEvents:UIControlEventEditingDidEndOnExit];
    filed_phone.keyboardType=UIKeyboardTypeNumberPad;
    filed_phone.delegate=self;
    [filed_phone addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"phonenumber"] != nil && [[[NSUserDefaults standardUserDefaults] objectForKey:@"logout"] isEqualToString:@"1"]) {
        filed_phone.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"phonenumber"];
    }
    
    [imageview addSubview:filed_phone];
    
    // 添加下拉按钮
    self.dropButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.dropButton.frame = CGRectMake(SCREEN_WIDTH-50*W-20*H, SCREEN_HEIGHT/2+35*H, 35*H, 20*H);
    self.dropButton.imageEdgeInsets = UIEdgeInsetsMake(0 * W, 5 * W, 0 * W, 5 * W);
    [self.dropButton setImage:[UIImage imageNamed:@"2pic_btn03_down"] forState:UIControlStateNormal];
    [self.dropButton addTarget:self action:@selector(dropButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [imageview addSubview:self.dropButton];
//    imageview addSubview:fie
   // [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(field_phonedidchange) name:UITextFieldTextDidChangeNotification object:filed_phone];
    image_pwd=[[UIImageView alloc]initWithFrame:CGRectMake(30*W, SCREEN_HEIGHT/2+70*H, SCREEN_WIDTH-60*W, 30*H)];
    image_pwd.image=[UIImage imageNamed:@"2pic_input"];
    [imageview addSubview:image_pwd];
    
    image_pwd_icon=[[UIImageView alloc]initWithFrame:CGRectMake(45*W, SCREEN_HEIGHT/2+75*H, 20*H, 20*H)];
    image_pwd_icon.image=[UIImage imageNamed:@"2pic_icon02"];
    [imageview addSubview:image_pwd_icon];
    
    field_pwd=[[UITextField alloc]initWithFrame:CGRectMake(50*W+20*H, SCREEN_HEIGHT/2+75*H, SCREEN_WIDTH-150*W, 20*H)];
    field_pwd.placeholder=@"请输入密码";
    field_pwd.secureTextEntry=YES;
    field_pwd.textColor=[UIColor whiteColor];
    field_pwd.font=[UIFont systemFontOfSize:13];
    field_pwd.delegate=self;
    [field_pwd addTarget:self action:@selector(keyboard_exit) forControlEvents:UIControlEventEditingDidEndOnExit];
    [imageview addSubview:field_pwd];

    btn_pwd_security=[[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-50*W-20*H, SCREEN_HEIGHT/2+75.5*H, 35*H, 20*H)];
    btn_pwd_security.imageEdgeInsets = UIEdgeInsetsMake(0 * W, 5 * W, 0 * W, 5 * W);
    [btn_pwd_security setImage:[UIImage imageNamed:@"2pic_password_on"] forState:UIControlStateNormal];
    [btn_pwd_security addTarget:self action:@selector(tapped_changefieldsecurity) forControlEvents:UIControlEventTouchUpInside];
    
    btn_pwd_security.tag=1;
    
    [imageview addSubview:btn_pwd_security];
    
    image_code=[[UIImageView alloc]initWithFrame:CGRectMake(30*W, SCREEN_HEIGHT/2+110*H, (SCREEN_WIDTH-60*W)/2, 30*H)];
    image_code.image=[UIImage imageNamed:@"code_input"];
//    [imageview addSubview:image_code];
    
    image_code_icon=[[UIImageView alloc]initWithFrame:CGRectMake(45*W, SCREEN_HEIGHT/2+115*H, 20*H, 20*H)];
    image_code_icon.image=[UIImage imageNamed:@"code_icon"];
//    [imageview addSubview:image_code_icon];

    _input=[[UITextField alloc]initWithFrame:CGRectMake(50*W+20*H, SCREEN_HEIGHT/2+115*H, (SCREEN_WIDTH-60*W)/2-45*W, 20*H)];
    _input.placeholder=@"请输入验证码";
    //_input.keyboardType=UIKeyboardTypeAlphabet;
    _input.textColor=[UIColor whiteColor];
    _input.font=[UIFont systemFontOfSize:13];
    _input.delegate=self;
    _input.secureTextEntry=YES;
    [_input addTarget:self action:@selector(keyboard_exit) forControlEvents:UIControlEventEditingDidEndOnExit];
//    [imageview addSubview:_input];
    
    _captchaView = [[CaptchaView alloc] initWithFrame:CGRectMake(40*W+(SCREEN_WIDTH-60*W)/2, SCREEN_HEIGHT/2+110*H, 100*W, 30*H)];
//    [self.view addSubview:_captchaView];
    
    btn_register=[[UIButton alloc]initWithFrame:CGRectMake(40*W, SCREEN_HEIGHT/2+150*H, 70*W, 20*H)];
    btn_register.backgroundColor=[UIColor clearColor];
    [btn_register setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn_register.titleLabel.font=[UIFont systemFontOfSize:12];
    [btn_register setTitle:@"账号激活" forState:UIControlStateNormal];
    [btn_register addTarget:self action:@selector(tapped_register) forControlEvents:UIControlEventTouchUpInside];
    [imageview addSubview:btn_register];
    
    btn_forgetpwd=[[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-110*W, SCREEN_HEIGHT/2+150*H, 70*W, 20*H)];
    btn_forgetpwd.backgroundColor=[UIColor clearColor];
    [btn_forgetpwd setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn_forgetpwd.titleLabel.font=[UIFont systemFontOfSize:12];
    btn_forgetpwd.titleLabel.textAlignment=NSTextAlignmentRight;
    [btn_forgetpwd addTarget:self action:@selector(tapped_forgetpwd) forControlEvents:UIControlEventTouchUpInside];
    [btn_forgetpwd setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [imageview addSubview:btn_forgetpwd];
       
    btn_login=[[UIButton alloc]initWithFrame:CGRectMake(35*W, SCREEN_HEIGHT/2+190*H, 100*W, 30*W)];
   // btn_login.enabled=NO;
    [btn_login setImage:[UIImage imageNamed:@"2pic_btn01"] forState:UIControlStateNormal];
    [btn_login addTarget:self action:@selector(tapped_login) forControlEvents:UIControlEventTouchUpInside];
    [imageview addSubview:btn_login];
    
    btn_tourist_login=[[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-135*W, SCREEN_HEIGHT/2+190*H, 100*W, 30*W)];
    [btn_tourist_login setImage:[UIImage imageNamed:@"2pic_btn02_on"] forState:UIControlStateNormal];
    [btn_tourist_login addTarget:self action:@selector(tapped_tourist) forControlEvents:UIControlEventTouchUpInside];
    [imageview addSubview:btn_tourist_login];
    
    
    // 添加滑动验证
    [self createSlider];
}

- (void)textFieldDidChange:(UITextField *)textField {

    // 暂时需要跟Android保持一致，先注释掉，待客户确认
//    self.phoneArr = [SaveManager readData];
//    // 根据输入状态模糊查询
//    if (textField.text.length != 0) {
//        self.dropValue = 0;
//        [self.tempArr removeAllObjects];
//        [self.dropScrollView removeFromSuperview];
//        for (NSString *tel in self.phoneArr) {
//            NSString *str = [tel substringToIndex:textField.text.length];
//            if ([str isEqualToString:textField.text]) {
//                if (self.tempArr.count == 0) {
//                    [self.tempArr addObject:tel];
//                }
//                else {
//                    for (NSString *phone in self.tempArr) {
//                        if ([phone isEqualToString:tel]) {
//                            [self.tempArr removeObject:phone];
//                            [self.tempArr addObject:tel];
//                        }
//                    }
//                    [self.tempArr addObject:tel];
//                }
//            }
//            else {
//                [self.dropScrollView removeFromSuperview];
//                image_phone.image = [UIImage imageNamed:@"2pic_input"];
//                [self.dropButton setImage:[UIImage imageNamed:@"2pic_btn03_down"] forState:UIControlStateNormal];
//            }
//        }
//        if (self.tempArr.count != 0) {
//            image_phone.image = [UIImage imageNamed:@"shuru2"];
//            [self.dropButton setImage:[UIImage imageNamed:@"2pic_btn03_up"] forState:UIControlStateNormal];
//            isDrop = YES;
//            [self createDropView];
//        }
//    }
//    else {
//        image_phone.image = [UIImage imageNamed:@"2pic_input"];
//        [self.dropButton setImage:[UIImage imageNamed:@"2pic_btn03_down"] forState:UIControlStateNormal];
//        [self.dropScrollView removeFromSuperview];
//    }
}

// 创建滑动验证视图
- (void)createSlider{
    _slider = [[CheckCodeSlider alloc]initWithFrame:CGRectMake(30*W, SCREEN_HEIGHT/2+110*H, SliderWidth, SliderHeight)];
    _slider.backgroundColor = [UIColor colorWithRed:16 / 255.0 green:104 / 255.0 blue:201 / 255.0 alpha:1.0];
//    _slider.center = self.view.center;
    _slider.minimumTrackTintColor = [UIColor clearColor];
    _slider.maximumTrackTintColor = [UIColor clearColor];
    _slider.layer.masksToBounds = YES;
    _slider.layer.cornerRadius = SliderHeight/2;
    [_slider setThumbImage:[UIImage imageNamed:@"2pic_btn03_up"] forState:UIControlStateNormal];
    [_slider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_slider];
    _charactersLabel = [[UILabel alloc]initWithFrame:CGRectMake(30*W, SCREEN_HEIGHT/2+110*H, SliderWidth, SliderHeight)];
    _charactersLabel.text = SliderLabelText;
    _charactersLabel.font = [UIFont systemFontOfSize:SliderLabelFont];
    _charactersLabel.textAlignment = NSTextAlignmentCenter;
    _charactersLabel.textColor = SliderLabelTextColor;
    _charactersLabel.layer.masksToBounds = YES;
    _charactersLabel.layer.cornerRadius = SliderHeight/2;
    _charactersLabel.layer.borderWidth = 1;
    _charactersLabel.layer.borderColor = SliderLabelBorderColor;
    [self.view addSubview:_charactersLabel];
    //这里创建了一个跟滑块相同的imageview覆盖在文字上面，并在sliderValueChanged方法中让其跟着滑块滑动。
    slideImgView = [[UIImageView alloc]initWithFrame:CGRectMake(_slider.frame.origin.x - 2, _slider.frame.origin.y, ThumbImageWidth, ThumbImageHeight)];
    slideImgView.backgroundColor = [UIColor whiteColor];
    slideImgView.image = [UIImage imageNamed:@"2pic_slide_arrow02"];
    slideImgView.layer.cornerRadius = ThumbImageHeight / 2;
    [self.view addSubview:slideImgView];
}
- (void)sliderValueChanged:(UISlider *)slider{
    [_slider setValue:slider.value animated:NO];
    if (slider.value >0) {
        _slider.minimumTrackTintColor = SliderMinimumTrackTintColor;
    }else{
        _slider.minimumTrackTintColor = [UIColor clearColor];
    }
    slideImgView.center = CGPointMake(_slider.frame.origin.x+slider.value*(SliderWidth-ThumbImageWidth)+ThumbImageWidth/2, _slider.frame.origin.y+ThumbImageHeight/2);
    if (!slider.isTracking && slider.value != 1) {
        [_slider setValue:0 animated:YES];
        if (slider.value >0) {
            _slider.minimumTrackTintColor = SliderMinimumTrackTintColor;
        }else{
            _slider.minimumTrackTintColor = [UIColor clearColor];
        }
        slideImgView.frame = CGRectMake(_slider.frame.origin.x-2, _slider.frame.origin.y, ThumbImageWidth, ThumbImageHeight);
    }
    if (_slider.value == 1) {
        NSLog(@"验证成功");
    }
}

// 添加下拉框view
- (void)createDropView {

    self.dropScrollView = [[UIScrollView alloc]init];
    self.dropScrollView.backgroundColor = RGBACOLOR(0, 131, 242, 1.0);
    self.dropScrollView.bounces = NO;
    self.dropScrollView.layer.borderWidth = 1;
    self.dropScrollView.layer.borderColor = RGBACOLOR(118, 200, 248, 1.0).CGColor;
    NSMutableArray *telArray = [NSMutableArray array];
    // 判断下拉框是点击出来的还是根据模糊查询出来的，上面模糊查询暂时注释掉，目前不管
    if (self.dropValue == 1) {
        telArray = [SaveManager readData];
    }
    else {
        telArray = [NSArray arrayWithArray:self.tempArr];
    }
    if (telArray.count == 0) {
        image_phone.image = [UIImage imageNamed:@"2pic_input"];
    }
    if (telArray.count <= 6) {
        self.dropScrollView.frame = CGRectMake(30*W, SCREEN_HEIGHT/2+30*H + 30 * H, SCREEN_WIDTH-60*W, 30 * telArray.count * H);
    }
    else {
        self.dropScrollView.frame = CGRectMake(30*W, SCREEN_HEIGHT/2+30*H + 30 * H, SCREEN_WIDTH-60*W, 180 * H);
    }
    self.dropScrollView.contentSize = CGSizeMake(SCREEN_WIDTH-60*W, telArray.count * 30 * H);
    for (int i = 0; i < telArray.count; i++) {
        UIButton *telButton = [UIButton buttonWithType:UIButtonTypeCustom];
        telButton.frame = CGRectMake(0, 30 * H * i, SCREEN_WIDTH-60*W, 30 * H);
        telButton.tag = 100 + i;
        [telButton setTitle:[NSString stringWithFormat:@"%@",telArray[i]] forState:UIControlStateNormal];
        [telButton setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
        telButton.backgroundColor = [UIColor clearColor];
        [telButton addTarget:self action:@selector(telButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.btnArray addObject:telButton];
        // 添加显示号码的Label
        UILabel *telLabel = [[UILabel alloc]initWithFrame:CGRectMake(40 * W, 0, SCREEN_WIDTH-150*W, 30 * H)];
        telLabel.backgroundColor = [UIColor clearColor];
        telLabel.text = [NSString stringWithFormat:@"%@",telArray[i]];
        telLabel.textColor = [UIColor whiteColor];
        telLabel.font = [UIFont systemFontOfSize:13.0];
        [telButton addSubview:telLabel];
        // 添加删除号码按钮
        UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        deleteBtn.frame = CGRectMake(SCREEN_WIDTH-75*W-20*H, 0, 25 * H, 25 * H);
        deleteBtn.imageEdgeInsets = UIEdgeInsetsMake(6, 6, 6, 6);
        [deleteBtn setImage:[UIImage imageNamed:@"x1"] forState:UIControlStateNormal];
        [deleteBtn addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [telButton addSubview:deleteBtn];
        [self.dropScrollView addSubview:telButton];
    }
    [self.view addSubview:self.dropScrollView];
}

-(void)dorequestforCheckVersion{
    NSString *newurl=[urlstring stringByAppendingString:@"checkVersion.do"];
    NSDictionary *dic=@{@"vesionid":CurrentVersion,@"type":@"1"};
    
    
    //网络请求操作
    [K_AppDelegate GenerateHTTPRequestWithUrl:newurl withParam:dic success:^(AFHTTPRequestOperation *op,id responseObject){
        NSDictionary *responseDic=(NSDictionary *)responseObject;
        NSString *msg=[responseDic objectForKey:@"msg"];
        //NSInteger flag=responseDic[@"flag"];
        NSString *flag=[responseDic objectForKey:@"flag"];
        NSInteger flag1=[flag longLongValue];
        NSString *force=[responseDic objectForKey:@"isForcedToUpload"];
        intforce=[force integerValue];
        
        if(flag1 == 1){
            newvesionurl=[responseDic objectForKey:@"newVersionUrl"];
            if(intforce==0){
                alert0=[[UIAlertView alloc]initWithTitle:@"当前有新版本,是否需要升级" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
                [alert0 show];
            }
            else if(intforce==1){
                alert1=[[UIAlertView alloc]initWithTitle:@"当前有新版本,需要强制升级" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"确认", nil];
                [alert1 show];
            }
        }
        if(msg){
            NSString *message=[msg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            //[PopMsg showMessage:message Lasttime:1.0f];
        }

        NSLog(@"111");
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        NSLog(@"222");
        [PopMsg showMessage:@"网络出错" Lasttime:1.0f];
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if(alertView==alert0){
        switch (buttonIndex) {
            case 0:
                NSLog(@"0");
                break;
                
            case 1:{
                //[[UIApplication sharedApplication]openURL:[NSURL URLWithString:newvesionurl]];
                NSString *iTunesString = [[NSUserDefaults standardUserDefaults]objectForKey:APP_URL];
                if(iTunesString){
                    NSURL *iTunesURL = [NSURL URLWithString:iTunesString];
                    [[UIApplication sharedApplication] openURL:iTunesURL];
                }
                else{
                    [PopMsg showMessage:@"无法打开AppStore" Lasttime:1.0f];
                }
                break;
            }
            default:
                break;
        }
    }
    else if(alertView==alert1){
        //[[UIApplication sharedApplication]openURL:[NSURL URLWithString:newvesionurl]];
        NSString *iTunesString = [[NSUserDefaults standardUserDefaults]objectForKey:APP_URL];
        if(iTunesString){
            NSURL *iTunesURL = [NSURL URLWithString:iTunesString];
            [[UIApplication sharedApplication] openURL:iTunesURL];
        }
        else{
            [PopMsg showMessage:@"无法打开AppStore" Lasttime:1.0f];
        }
    }
}

#pragma mark -- 点击事件
// 下拉框点击事件
- (void)dropButtonAction:(UIButton *)sender {

    self.dropValue = 1;
    if (isDrop == NO) {
        isDrop = YES;
        [sender setImage:[UIImage imageNamed:@"2pic_btn03_up"] forState:UIControlStateNormal];
        NSMutableArray *array = [SaveManager readData];
        if (array.count != 0) {
            image_phone.image = [UIImage imageNamed:@"shuru2"];
        }

        [self createDropView];
    }
    else {
        isDrop = NO;
        [sender setImage:[UIImage imageNamed:@"2pic_btn03_down"] forState:UIControlStateNormal];
        image_phone.image = [UIImage imageNamed:@"2pic_input"];
        [self.dropScrollView removeFromSuperview];
    }
    NSLog(@"选择号码");
}

// 选择号码点击事件,存储的数据进行展现
- (void)telButtonClick:(UIButton *)sender {

    filed_phone.text = sender.titleLabel.text;
    [self.dropScrollView removeFromSuperview];
    isDrop = NO;
    [self.dropButton setImage:[UIImage imageNamed:@"2pic_btn03_down"] forState:UIControlStateNormal];
    image_phone.image = [UIImage imageNamed:@"2pic_input"];
//    sender.backgroundColor = RGBACOLOR(166, 222, 249, 1.0);
}

// 删除号码点击事件
- (void)deleteBtnClick:(UIButton *)sender {

    UIButton *chooseButton = (UIButton *)sender.superview;
    NSMutableArray *telArray = [SaveManager readData];
    for (NSString *telString in telArray) {
        if ([chooseButton.titleLabel.text isEqualToString:telString]) {
            [telArray removeObject:telString];
            break;
        }
    }
    for (NSString *phone in self.tempArr) {
        if ([chooseButton.titleLabel.text isEqualToString:phone]) {
            [self.tempArr removeObject:phone];
            break;
        }
    }
    [[SaveManager sharedSaveManager] saveDataWithArray:telArray];
    //移除下拉的表示图
    [self.dropScrollView removeFromSuperview];
    [self createDropView];
}

-(void)tapped_forgetpwd{
    ForgetpwdViewController *forgetpwdview=[ForgetpwdViewController new];
    UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:forgetpwdview];
    [self presentViewController:nav animated:YES completion:nil];
}

-(void)tapped_register{
    RegisterViewController *registerview=[RegisterViewController new];
    UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:registerview];
    [self presentViewController:nav animated:YES completion:nil];
    
}




//游客身份登陆系统进行操作
-(void)tapped_tourist{
//    [self presentViewController:[TouristViewController new] animated:YES completion:nil];
    start = YES;
    end = YES;
    NSString *forvenderid =
    [[UIDevice currentDevice].identifierForVendor UUIDString];
    
    
    PopLoadMsg *loadmsg = [[PopLoadMsg alloc] init];
    // NSString *url=@"http://appif.jszhtech.com:8080/ebappif/appif/login.do";
    NSString *url = [urlstring stringByAppendingString:@"login.do"];
    NSDictionary *dic = @{
                          @"loginId" : @"guest",
                          @"loginPwd" : @"123456",
                          @"type" : @"IOS",
                          @"devide" : forvenderid,
                          @"registrationId" : [APService registrationID]
                          };
    
    
    NSLog(@"hhhhhhhh %@   %@",forvenderid,[APService registrationID]);
    
    
    

    
    dispatch_async(
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                       sleep(startloadtime);
                       dispatch_async(dispatch_get_main_queue(), ^{
                           if (start == YES) {
                               [loadmsg loadImages];
                           }
                       });
                   });
    
    dispatch_async(
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                       sleep(startloadtime + endloadtime);
                       dispatch_async(dispatch_get_main_queue(), ^{
                           end = NO;
                           if (start == NO) {
                               [loadmsg.imageview removeFromSuperview];
                           }
                       });
                   });
    __weak __typeof(self)wself = self;
    [K_AppDelegate GenerateHTTPRequestWithUrl:url
                                    withParam:dic
                                      success:^(AFHTTPRequestOperation *op, id responseObject) {
                                          NSLog(@"111");
                                          start = NO;
                                          if (end == NO) {
                                              [loadmsg.imageview removeFromSuperview];
                                          }
                                          
                                          NSDictionary *responseDic = (NSDictionary *)responseObject;
                                          NSString *msg = [responseDic objectForKey:@"msg"];
                                          NSString *flag = [responseDic objectForKey:@"flag"];
                                          NSInteger flagphone = [flag integerValue];
                                          
                                     
                                          if (msg) {
                                              NSString *message =
                                              [msg stringByReplacingPercentEscapesUsingEncoding:
                                               NSUTF8StringEncoding];
                                              [PopMsg showMessage:message Lasttime:1.0f];
                                          }
                                          if (flagphone == 0) {
                                              //成功登陆
                                              NSLog(@"成功登录");
                                              self.userOrTourist = @"0";
                                              [[NSUserDefaults standardUserDefaults] setObject:self.userOrTourist forKey:@"userOrTourist"];
                                              [[NSUserDefaults standardUserDefaults] setObject:@"guest" forKey:@"phonenumber"];
                                              RootviewConrtoller *rootVC = [[RootviewConrtoller alloc]init];
                                              self.view.window.rootViewController = rootVC;
                                          }
                                          
                                      }
                                      failure:^(AFHTTPRequestOperation *op, NSError *error) {
                                          NSLog(@"222");
                                          start = NO;
                                          if (end == NO) {
                                              [loadmsg.imageview removeFromSuperview];
                                          }
                                          [PopMsg showMessage:@"网络出错" Lasttime:1.0f];
                                      }];

}




- (void)tapped_login {
  start = YES;
  end = YES;
  NSString *forvenderid =
      [[UIDevice currentDevice].identifierForVendor UUIDString];

  PopLoadMsg *loadmsg = [[PopLoadMsg alloc] init];
  // NSString *url=@"http://appif.jszhtech.com:8080/ebappif/appif/login.do";
  NSString *url = [urlstring stringByAppendingString:@"login.do"];

  NSComparisonResult result = [_input.text compare:_captchaView.changeString
                                           options:NSCaseInsensitiveSearch];

  if (filed_phone.text.length == 0 || filed_phone == nil) {
    [PopMsg showMessage:@"手机号码不能为空" Lasttime:1.0f];
  } else if (filed_phone.text.length < 11) {
    [PopMsg showMessage:@"手机号码位数不对" Lasttime:1.0f];
  }

  else if (field_pwd.text.length == 0 || field_pwd == nil) {
    [PopMsg showMessage:@"密码不能为空" Lasttime:1.0f];
  } else if (field_pwd.text.length < 6 || field_pwd.text.length > 12) {
    [PopMsg showMessage:@"密码长度不正确" Lasttime:1.0f];
  } else if (_slider.value != 1) {
    [PopMsg showMessage:@"请先解锁，再登录" Lasttime:1.0f];
    [_captchaView changeCaptcha];
    [_captchaView setNeedsDisplay];
  } else {
    NSDictionary *dic = @{
      @"loginId" : filed_phone.text,
      @"loginPwd" : field_pwd.text,
      @"type" : @"IOS",
      @"devide" : forvenderid,
      @"registrationId" : [APService registrationID]
    };

    dispatch_async(
        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
          sleep(startloadtime);
          dispatch_async(dispatch_get_main_queue(), ^{
            if (start == YES) {
              [loadmsg loadImages];
            }
          });
        });

    dispatch_async(
        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
          sleep(startloadtime + endloadtime);
          dispatch_async(dispatch_get_main_queue(), ^{
            end = NO;
            if (start == NO) {
              [loadmsg.imageview removeFromSuperview];
            }
          });
        });
      __weak __typeof(self)wself = self;
    [K_AppDelegate GenerateHTTPRequestWithUrl:url
        withParam:dic
        success:^(AFHTTPRequestOperation *op, id responseObject) {
          NSLog(@"111");
          start = NO;
          if (end == NO) {
            [loadmsg.imageview removeFromSuperview];
          }

            NSLog(@"dasqeqwe12321  %zd",[[responseObject objectForKey:@"bidlist"] count] );
        
            NSDictionary *responseDic = (NSDictionary *)responseObject;
          NSString *msg = [responseDic objectForKey:@"msg"];
          NSString *flag = [responseDic objectForKey:@"flag"];
          NSInteger flagphone = [flag integerValue];
          if (msg) {
            NSString *message =
                [msg stringByReplacingPercentEscapesUsingEncoding:
                         NSUTF8StringEncoding];
            [PopMsg showMessage:message Lasttime:1.0f];
          }
          if (flagphone == 0) {
            //成功登陆
            [[NSUserDefaults standardUserDefaults] setObject:@"1"
                                                      forKey:@"judgeNo"];
            [[NSUserDefaults standardUserDefaults] setObject:filed_phone.text
                                                      forKey:@"phonenumber"];
            [[NSUserDefaults standardUserDefaults] setObject:field_pwd.text
                                                      forKey:@"password"];
            NSArray *array = [responseDic objectForKey:@"bidlist"];
            if (array.count != 0 && array != nil) {
              NSDictionary *dic_bid = array[0];
              NSString *bid = [dic_bid objectForKey:@"bid"];
              
                
            
                
              [[NSUserDefaults standardUserDefaults] setObject:bid
                                                        forKey:@"bid"];
                
            }
            else
            {
              
                [PopMsg showMessage:@"不能获得用户注册信息" Lasttime:1.0f];
                return ;

              
            }

              // 保存号码
              NSMutableArray *telArray = [SaveManager readData];
              if (telArray.count == 0) {
                  NSMutableArray *phoneArr = [NSMutableArray array];
                  [phoneArr addObject:filed_phone.text];
                  [[SaveManager sharedSaveManager] saveDataWithArray:phoneArr];
              }
              else {
                  int count = 0;
                  for (NSString *tel in telArray) {
                      if ([tel isEqualToString:filed_phone.text]) {
                          count++;
                      }
                  }
                  if (count == 0) {
                      [telArray addObject:filed_phone.text];
                      [[SaveManager sharedSaveManager] saveDataWithArray:telArray];
                  }
              }
              
              wself.userOrTourist = @"1";
              [[NSUserDefaults standardUserDefaults] setObject:wself.userOrTourist forKey:@"userOrTourist"];
              wself.view.window.rootViewController = [RootviewConrtoller new];
            
          }

        }
        failure:^(AFHTTPRequestOperation *op, NSError *error) {
          NSLog(@"222");
          start = NO;
          if (end == NO) {
            [loadmsg.imageview removeFromSuperview];
          }
          [PopMsg showMessage:@"网络出错" Lasttime:1.0f];
        }];

    }
}

- (void)field_phonedidchange {
  if (filed_phone.text.length == 11) {
    btn_login.enabled = YES;
  } else {
    btn_login.enabled = NO;
  }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *cs;
    if(textField==filed_phone)
    {
        cs = [[NSCharacterSet characterSetWithCharactersInString:kNumbers] invertedSet];
        if (textField.text.length >= 11)
        {
            if ([string isEqual:@""])
            {
                return YES;
            }
            return NO;
        }
    }
    else
    {
        cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
        if(textField==field_pwd)
        {
            if (textField.text.length >= 12)
            {
                if ([string isEqual:@""])
                {
                    return YES;
                }
                return NO;
            }

        }
        else if(textField==_input)
        {
            _input.secureTextEntry=NO;
            if (textField.text.length >= 4)
            {
                if ([string isEqual:@""])
                {
                    return YES;
                }
                return NO;
            }
        }
    }
    NSString *filtered =
    [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL basic = [string isEqualToString:filtered];
    
    return basic;
}

-(void)tapped_changefieldsecurity{
    if(btn_pwd_security.tag==1){
        field_pwd.secureTextEntry=NO;
        btn_pwd_security.tag=2;
        [btn_pwd_security setImage:[UIImage imageNamed:@"2pic_password_off"] forState:UIControlStateNormal];
    }
    else if(btn_pwd_security.tag==2){
        field_pwd.secureTextEntry=YES;
        btn_pwd_security.tag=1;
        [btn_pwd_security setImage:[UIImage imageNamed:@"2pic_password_on"] forState:UIControlStateNormal];
    }
}

-(void)keyboard_exit{
   
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  [filed_phone resignFirstResponder];
  [field_pwd resignFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"logout"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
